//
// Copyright (c) 2014, 保留所有权利。
//
// ContractSync.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 下午1:16:13
//
// 
//
package com.vanke.agent.sync;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.Cfg;
import com.vanke.agent.common.CstUtil;

/**
 *
 */
public class HpointSync extends AgentSync {
	Logger log = Logger.getLogger(HpointSync.class);
	String table = "h_Point";
	String fields = C.FIELDS_POINT;

	@Override
	public void sync() {
		log.info("=============sync new h_Point===========");
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_MY);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);

		try {

			String timeStr = dateFormat.format(pointCfg.beginTime);
			pointCfg.beginTime = new Date(System.currentTimeMillis());

			String querySql = "SELECT " + fields + "  FROM " + table;
			querySql += " where PointDate > ? and PointDate < ? "
					+ "order by PointDate asc";
			log.info("execute: " + querySql + "[" + timeStr + "]");

			String insertSql = CstUtil.formatInsertSql(table, fields);
			PreparedStatement wpstmt = wcon.prepareStatement(insertSql);
			int columns = fields.split(",").length;

			PreparedStatement pstmt = con.prepareStatement(querySql);
			pstmt.setString(1, timeStr);
			pstmt.setString(2, dateFormat.format(pointCfg.beginTime));

			ResultSet rs = pstmt.executeQuery();
			int count = 0;
			if (!rs.next()) {
				log.info("no h_Point is created");
				ADataSource.close(rs);
				ADataSource.close(pstmt);
				return;
			}
			do {
				try {
					for (int i = 1; i <= columns; i++) {
						wpstmt.setString(i, rs.getString(i));
					}
					wpstmt.executeUpdate();
					count++;

				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				}

			} while (rs.next());

			// 保存配置，最后一次的时间
			Cfg.set(pointCfg.cfgKey,
					dateFormat.format(pointCfg.beginTime));
			Cfg.save();

			// 关闭
			ADataSource.close(rs);
			ADataSource.close(pstmt);
			ADataSource.close(wpstmt);

			log.info(count + " point synced");
			log.info("=============sync point end===========");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(con);
			ADataSource.close(wcon);
		}
	} // ~sync

}
